package com.sleepless.my.io;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;

@AllArgsConstructor
public class RestBean {
    public int code;
    public String msg;
    public Object data;

    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static  Object success() {
//        return JSON.toJSONString(new RestBean(0, "", ""));
        return new RestBean(0, "", "");
    }

    public static  Object success(Object data) {
        return new RestBean(0, "", data);
    }

    public static Object failure(int status, String message) {
        return new RestBean(status, message, null);
    }

    public static Object failure(Code code) {
        return new RestBean(code.ordinal(), code.name(), null);
    }

    public static Object handlerError(Object data) {
        if (data instanceof Code) {
            return failure((Code) data);
        } else if (data == null) {
            return failure(0, "服务错误");
        }
        return null;
    }

    public static String serialize(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return "{}";
        }
    }

    public static String serializeFailure(int status, String message) {
        return serialize(failure(status,message));
    }

    public static String serializeFailure(Code code) {
        return serialize(failure(code));
    }

    public static String serializeSuccess(Object data) {
        return serialize(success(data));
    }

    public static String unImpl="未完成的接口";

    public enum  Code{
        服务错误,
        权限不足,
        参数校验错误,
        认证失败,
        未授权,
        用户ID为空,
        用户名为空,
        密码为空,
        密码长度小于六个字符,
        用户名已存在,
        视频标题不能为空,
        视频描述不能为空,
        视频类型不能为空,
        上传视频失败,
        上传图片失败,
        用户不存在,
        视频ID为空,
        视频不存在,
        评论不存在,
    }
}
